import json

from comment.comviews import err_response

import logging


def get_body(request):
    """
    获得返回数值
    :param request:
    :return:
    """
    try:
        body = json.loads(request.body)
        return body
    except Exception as e:
        logging.error("「getbody」:{}".format(e))
        return err_response(505)


def get_params(body, params=None, null_params=None, **replace_null):
    """
    序列化请求
    :param body:dict
    :param params:dict 必要参数
    :param null_params:dict 非必要参数
    :param replace_null: 非必要替换参数
    :return:
    """
    try:
        if not isinstance(body, dict):
            return err_response(210)
        params_dict = {}
        if params:
            for key, param in params.items():
                if body.get(param) is None:
                    return err_response(212, "'{}' params is null".format(param))
                params_dict[key] = body.get(param)
            # params_dict[key] = body.get(param)
                # if not all(params_dict):
                #     return err_response(212, "'{}' params is null".format(param))
        if null_params:
            for key, null_param in null_params.items():
                value = body.get(null_param)
                # params_dict[key] = value
                if value is None:
                    params_dict[key] = replace_null.get(null_param)
                else:
                    params_dict[key] = value
        return params_dict
    except Exception as e:
        logging.error("「get_params」:{}".format(e))
        return err_response(210)


def get_params_exitnull(body, params=None, null_params=None, **replace_null):
    """
    序列化请求
    :param body:dict
    :param params:dict 必要参数
    :param null_params:dict 非必要参数
    :param replace_null: 非必要替换参数
    :return:
    """
    try:
        params_dict = {}
        if params:
            for key, param in params.items():
                params_dict[key] = body.get(param)
                if not all(params_dict):
                    return err_response(505, "'{}' params is null".format(param))
        if null_params:
            for key, null_param in null_params.items():
                value = body.get(null_param)
                if not value:
                    value = replace_null.get(null_param)
                    if value:
                        params_dict[key] = value
                else:
                    params_dict[key] = value
        return params_dict
    except Exception as e:
        logging.error("「get_params_exitnull」:{}".format(e))
        return err_response(505)
